const { validate, errorResponese, successResponese } = require("../utils/validate")
const UserSchema = require("../schema/UserSchema")
const UserService = require("../services/UserServices")
const { encrypto } = require("../utils/crypto")
const UserModel = require("../model/UserModel")
const { filterQuery,handleReg } = require("../utils/tools")
const fs = require("fs")
const path = require("path")
const UserController = {
    // 用户查找
    find: async (req, res) => {
        const { pages, params } = filterQuery(req.query)
        let findFields = ["username", "nickname", "status", "telephone","createTime","department","email","gender","idnumber"]
        const data = await UserService.find(handleReg(req.query,findFields),pages)
        // 根据查询条件获取数据总条目
        let total = await UserModel.count(params)
        res.send({
            code: "200",
            msg: "用户查询成功",
            total,
            data,
        })
    },
    // 增加用户
    append: async (req, res) => {
        // 校验参数
        const v = await validate(UserSchema.append, req.body)

        if (v) return errorResponese({ res: res, msg: v })

        // 判断新增的用户名是否重复
        const data = await UserService.find({ username: req.body.username })

        if (data.length !== 0) return errorResponese({
            res: res,
            code: "400",
            msg: "用户名重复"
        })

        // 密码加密
        req.body.password = encrypto(req.body.password)
        // 处理图片上传
        let avatar
        if (req.file) {
            avatar = `/uploads/${req.file.filename}`
        } else {
            avatar = "/images/default.jpg"
        }
        const otherinfo = {
            avatar: avatar,
        }
        // 添加到数据库
        let result =  await UserService.append(Object.assign(req.body, otherinfo))
        result && successResponese({
            res: res,
            msg: "用户添加成功",
        })

    },
    // 修改用户
    update: async (req, res) => {
        // 修改头像
        if(req.body.type === "avatar") {
            return UserController.avatar(req,res)
        }
        // // 修改密码
        if (req.body.type === "password") {
          return  UserController.password(req,res)
        }
        if (req.body.type === "sort") {
            return UserController.sort(req,res)
        }
        // 修改整条信息
        // 校验参数
        const v = await validate(UserSchema.update, req.body)
        if (v) return errorResponese({ res: res, msg: v })
        const userinfo = req.body
        delete userinfo.password
        const data = await UserService.update(userinfo)
        if (!data) return errorResponese({ res: res, msg: "修改用户失败" })
        successResponese({ res: res, msg: "修改用户成功" })
    },
    // 删除用户
    remove: async (req, res) => {
        let data
        try {
            data = await UserService.remove(req.params.id)
        } catch (error) {

        }
        if (!data) return errorResponese({ res: res, msg: "删除用户失败" });

        successResponese({ res: res, msg: "删除用户成功" })
    },
    // 用户排序
    sort: async (req, res) => {
        for (let i = 0; i < req.body.data.length; i++) {
            const item = req.body.data[i];
            await UserService.update(item).then().catch(error => {
                errorResponese({
                    res: res,
                    msg: `用户${item._id}排序失败`
                })
            })
        }
        successResponese({
            res: res,
            msg: "用户修改成功"
        })
    },
    // 修改密码
    password:async (req,res)=>{
        const {oldPassword,newPassword,_id} = req.body
       
        let psd = encrypto(oldPassword)
        let result = await UserModel.findOne({_id,}, ["password"])
      
        if (newPassword.length<6|| newPassword.length > 16) {
           return errorResponese({
                res:res,
                msg:"密码应在6-16位字符"
            })
        }
        if (psd !== result.password) {
            return errorResponese({
                res:res,
                msg:"密码输入错误"
            })
        }
        const data = await UserService.update({_id,password:encrypto(newPassword)})
        if (!data) return errorResponese({ res: res, msg: "修改用户失败" })
        successResponese({ res: res, msg: "修改用户成功" })
    },
    avatar: async(req,res)=>{
        if (!req.body._id || !req.file) return errorResponese({
            res:res,
            msg:"id和图片文件为必填项"
        })

        const {_id} = req.body
        let result = await UserModel.findOne({_id,}, ["avatar"])

        let avatar = ""
        if (result.avatar === "/images/default.jpg") {
            avatar   = `/uploads/${req.file.filename}`
        } else {
            const filePath = path.join(__dirname,`../public${result.avatar}`)
            fs.unlink(filePath, (err) => {
                console.log(err);
            })
            avatar   = `/uploads/${req.file.filename}`
        }
       
        let data = await UserService.update({_id,avatar:avatar})
        data && successResponese({
            res: res,
            msg: "头像修改成功",
            data:avatar
        })
    }   
}

module.exports = UserController